package village.rainbow.dailyscene.uicontrol;

import village.rainbow.dailyscene.R;
import village.rainbow.dailyscene.datamodel.DataRow;
import village.rainbow.dailyscene.datamodel.DataTable;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.Button;
import android.widget.LinearLayout;

/**
 * Tab Control 
 * for use variety case
 * 
 * Four state
 * 1. Not scrollable : left, right arrow disabled
 * 2. Edge of left : left arrow disabled / right arrow enabled
 * 3. Edge of right : right arrow disabled / left arrow enabled
 * 4. middle of scroll : left/right arrow enabled  
 * 
 * @author Kwon
 *
 */
public class TabLayout extends LinearLayout {

	public static final boolean SHOW_ARROW = true;
	public static final boolean UNSHOW_ARROW = false;
	
	private int TAB_BTN_COLOR = 0;
	
	private Context mContext;
	private LinearLayout mLeftBtnBase;
	private LinearLayout mRightBtnBase;
	
	private int mWholeHeight = 0;
	
	private UiPagingScrollView mUiPagingScrollView;
	
	private int mLayoutWidth = 686;
	
	public TabLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.mContext = context;
	}

	public TabLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = context;
	}

	public TabLayout(Context context) {
		super(context);
		this.mContext = context;
	}
	
	public void setTabBtnColorMode(int color){
		TAB_BTN_COLOR = color;
	}
	
	private int mInflateBaseWidth;
	
	
	public void init(final boolean showArrow){
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity)mContext).getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		int layoutHeight = (int)(68*metrics.density);
		mWholeHeight = layoutHeight;
		
		// TODO : this.getWidth()로 정상적인 width가 뽑혀져 나오질 않아서 임시로 계산해서 넣음 고쳐야함
		int layoutWidth = (int) (metrics.widthPixels - (45*metrics.density)); //(int)(mLayoutWidth*metrics.widthPixels);
		
		this.setLayoutParams(new LinearLayout.LayoutParams(layoutWidth, layoutHeight));
		this.setGravity(Gravity.CENTER_VERTICAL);
		this.setOrientation(LinearLayout.HORIZONTAL);
		
		final Drawable leftArrowOff = mContext.getResources().getDrawable(R.drawable.left_arrow);
		final Drawable rightArrowOff = mContext.getResources().getDrawable(R.drawable.right_arrow);
		final Drawable leftArrowOn = mContext.getResources().getDrawable(R.drawable.left_arrow);
		final Drawable rightArrowOn = mContext.getResources().getDrawable(R.drawable.right_arrow);

		mLeftBtnBase = makeBtnLayout(leftArrowOff, layoutHeight, true);
		mRightBtnBase = makeBtnLayout(rightArrowOff, layoutHeight, false);
		if(showArrow)
			mInflateBaseWidth = layoutWidth -  ((int)(40*metrics.density));//(leftArrowOff.getIntrinsicWidth()*2 + rightArrowOff.getIntrinsicWidth()*2);
		else
			mInflateBaseWidth = layoutWidth;
		
		mUiPagingScrollView = new UiPagingScrollView(this.mContext, mInflateBaseWidth, layoutHeight){
			@Override
			public void onPageScrollCompleted(final int index, int totalCount) {
				this.post(new Runnable() {
					public void run() {
						
						if(!showArrow)
							return;
						
						// 페이지가 한개면 페이지 화살표 변경을 하지않는다.
						if(mUiPagingScrollView.getTotalPageCount() <= 1)
							return;
						
						// 첫 번째 페이지
						if(mUiPagingScrollView.getCurrentIndex() == 0){
							changeBtnBg(rightArrowOn, mRightBtnBase);
							changeBtnBg(leftArrowOff, mLeftBtnBase);
						}
						// 마지막 페이지
						else if(mUiPagingScrollView.getCurrentIndex() == mUiPagingScrollView.getTotalPageCount()-1){
							changeBtnBg(rightArrowOff, mRightBtnBase);
							changeBtnBg(leftArrowOn, mLeftBtnBase);
						}
						// 중간 페이지
						else{
							changeBtnBg(rightArrowOn, mRightBtnBase);
							changeBtnBg(leftArrowOn, mLeftBtnBase);
						}
					}
				});
			}
		};
		
		if(showArrow)
			this.addView(mLeftBtnBase);
		
		this.addView(mUiPagingScrollView);
		
		if(showArrow)
			this.addView(mRightBtnBase);

		this.invalidate();
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		
		if(changed){
			
		}
		
	}
	
  /**
	* init 먼저 해야함
	*/
	public void addChilds(final DataTable floorList,final String labelKey,final int firstClickIndex,final OnClickListener listener){
		
		Activity act = (Activity)mContext;
		act.runOnUiThread(new Runnable(){
			@Override
			public void run() {
				
				// 몫과 나머지를 구한다. 몫 : / (x), 나머지 : % (y)
				// 몫은 floorList.size()/x 로 페이징의 갯수를 구한다.
				// 나머지는 listSize 마지막 루프돌때 mInflateBaseWidth/y로 한 후에 값을 구한다.
				
				int 나머지 = floorList.size() % 3;
				
				mUiPagingScrollView.removeAllViews();
				
				LinearLayout layoutBase = new LinearLayout(mContext);
				layoutBase.setLayoutParams(new LinearLayout.LayoutParams(mInflateBaseWidth, mWholeHeight));
				
				LinearLayout layout = new LinearLayout(mContext);
				layout.setLayoutParams(new LinearLayout.LayoutParams(mInflateBaseWidth, mWholeHeight));
				
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(mInflateBaseWidth/3, mWholeHeight);
				
				// 3개씩 끊어간다.
				int lastIndex = 0;
				
				int listSize = floorList.size()/3;
				if(floorList.size()%3 != 0)
					listSize++;
				
				Button firstBtn = null;
				
				for(int i=0; i<listSize; i++){
					
					// 마지막을 돌 때
					if(i == (listSize - 1)){ 
						if (나머지 != 0)
							param = new LinearLayout.LayoutParams(mInflateBaseWidth/나머지, mWholeHeight);
						else{
							// 나머지가 0이면 3의 배수임
							param = new LinearLayout.LayoutParams(mInflateBaseWidth/3, mWholeHeight);
						}
					}	
					
					while(lastIndex < floorList.size()){
						DataRow row = floorList.get(lastIndex);
						row.put("TG_INDEX", i + "");
						String label = row.get(labelKey).toString();

						Button btn = new Button(mContext);
						btn.setTextColor(Color.WHITE);
						btn.setId(R.id.img_thumbnail);
						btn.setTag(row);
						btn.setOnClickListener(listener);
						btn.setText(label);
						
//						btn.setTextSize(fontSize/2.3f);
						btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
						btn.setLayoutParams(param);
						
						if(lastIndex == firstClickIndex)
							firstBtn = btn;
						
						lastIndex++;
						
						
						layout.addView(btn);
						
						if(lastIndex % 3 == 0)
							break;
						
					}
					layoutBase.addView(layout);
					layout = new LinearLayout(mContext);
				}

				mUiPagingScrollView.addView(layoutBase);
				mUiPagingScrollView.onPageScrollCompleted(mUiPagingScrollView.getCurrentIndex(), mUiPagingScrollView.getTotalPageCount());
				
				firstBtn.performClick();
			}
		});
		
	}

	/**
	 * FloorBtnView가 아니면 child 로 받아들이지 않겠다. !!!
	 * @param child
	 */
//	public void addChild(View child){
//		if(mInflateBase == null || !(child instanceof FloorBtnView))
//			return;
//		mInflateBase.addView(child);
//		this.invalidate();		
//	}
	
	private void changeBtnBg(Drawable drawable, LinearLayout btnBase){
		Button btn = (Button)btnBase.getChildAt(0);
		btn.setBackgroundDrawable(drawable);
		btn.invalidate();
	}

	private LinearLayout makeBtnLayout(Drawable drawable, int layoutHeight, boolean leftRight){
		int width = drawable.getIntrinsicWidth();

		LinearLayout btnBase = new LinearLayout(mContext);
//		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(width*2, layoutHeight);
		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(24, layoutHeight);
		btnBase.setLayoutParams(param);
		
		if(leftRight)
			btnBase.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
		else
			btnBase.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
		
		Button btn = new Button(mContext);
		btn.setBackgroundDrawable(drawable);

		int imageWidth = drawable.getIntrinsicWidth();
		int imageHeight = drawable.getIntrinsicHeight();
		
		param = new LinearLayout.LayoutParams(imageWidth, imageHeight);
		btn.setLayoutParams(param);
		btnBase.addView(btn);

		return btnBase;
	}

	public DataRow getCurrentSelectData(){
		DataRow row = null;
		for(int i=0; i<mUiPagingScrollView.getChildACount(); i++){
			LinearLayout layout = (LinearLayout) mUiPagingScrollView.getChildAtIndex(i);
			for(int j = 0; j < layout.getChildCount(); j++){
				final Button child = (Button)layout.getChildAt(j);
				if(child.getTag() == null)
					continue;
				
				row = (DataRow)child.getTag();
				break;
//				DataRow childRow = (DataRow) child.getTag();
//				if(row.get("TG_CD", "").toString().equals(childRow.get("TG_CD", "").toString())){
//					child.setToggle(true);
//				}else{
//					child.setToggle(false);
//				}
//				child.post(new Runnable(){
//					@Override
//					public void run() {
//						child.invalidate();		
//					}
//				});
			}
		}
		return row;
	}
	
	public void toggleOtherButton(int index, String key){
		int childIndex = 0;
		for(int i=0; i<mUiPagingScrollView.getChildACount(); i++){
			LinearLayout layout = (LinearLayout) mUiPagingScrollView.getChildAtIndex(i);
			for(int j = 0; j < layout.getChildCount(); j++){
				if(childIndex == index){
					final Button child = (Button)layout.getChildAt(j);
					child.performClick();
				}
				childIndex++;
			}
		}
	}

//	// 층버튼 토글링 메서드
	public void toggleOtherButton(final DataRow row) {
		this.toggleOtherButton(row, "TG_CD");
	}
	
	////////////////////////////////////////////////////////////////////////////////
	// 2013.09.23 KJW 추가
	
	/**
	 * 비교Key 값을 설정할수 있게 수정 (2013.09.23 KJW)
	 * @param row
	 */
	public void toggleOtherButton(final DataRow row, String key)
	{
		for(int i=0; i<mUiPagingScrollView.getChildACount(); i++){
			LinearLayout layout = (LinearLayout) mUiPagingScrollView.getChildAtIndex(i);
			for(int j = 0; j < layout.getChildCount(); j++){
				final Button child = (Button)layout.getChildAt(j);
				if(child.getTag() == null)
					continue;

				DataRow childRow = (DataRow) child.getTag();
				
//				if(row.get(key, "").toString().equals(childRow.get(key, "").toString())){
//					child.setToggle(true);
//				}else{
//					child.setToggle(false);
//				}
				child.post(new Runnable(){
					@Override
					public void run() {
						child.invalidate();		
					}
				});
			}
		}
	}
	
	////////////////////////////////////////////////////////////////////////////////
	
	public void setLayoutWidth(int layoutWidth)
	{
		mLayoutWidth = layoutWidth;
	}
	public int getLayoutWidth()
	{
		return mLayoutWidth;
	}
}
